鍍金池/ 問(wèn)答/HTML/ 包開發(fā)完webpack打包后,項(xiàng)目中引用報(bào) 'NODE_ENV' of unde

包開發(fā)完webpack打包后,項(xiàng)目中引用報(bào) 'NODE_ENV' of undefined

我引用了element的組件,想改造下做成自己的UI庫(kù),打包后引入項(xiàng)目,npm run dev運(yùn)行報(bào)了如下錯(cuò)誤:
引入的包:node_modules/ipst/dist/ipst.js報(bào)錯(cuò):

    Uncaught TypeError: Cannot read property 'NODE_ENV' of undefined
    at Object.eval (ipst.js?df1b:formatted:346)
    at t (ipst.js?df1b:formatted:15)
    at Object.eval (ipst.js?df1b:formatted:28432)
    at t (ipst.js?df1b:formatted:15)
    at Object.eval (ipst.js?df1b:formatted:8917)
    at t (ipst.js?df1b:formatted:15)
    at Object.eval (ipst.js?df1b:formatted:28432)
    at t (ipst.js?df1b:formatted:15)
    at Object.eval (ipst.js?df1b:formatted:28432)
    at t (ipst.js?df1b:formatted:15)

目錄結(jié)構(gòu):

clipboard.png

webpack.base.conf.js

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

const createLintingRule = () => ({
  test: /\.(js|vue)$/,
  loader: 'eslint-loader',
  enforce: 'pre',
  include: [resolve('src'), resolve('test')],
  options: {
    formatter: require('eslint-friendly-formatter'),
    emitWarning: !config.dev.showEslintErrorsInOverlay
  }
})

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    ipst: process.env.NODE_ENV === 'production'
        ? resolve('src/index.js')
        : resolve('example/main.js')
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
      'example': resolve('example'),
      'ele': resolve('/src/lib/ele-components'),
    }
  },
  module: {
    rules: [
      ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

webpack.prod.conf.js

'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

const env = config.build.env

const webpackConfig = merge(baseWebpackConfig, {
  externals:{
    'vue':'vue'
  },
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: config.build.assetsPublicPath,
    library: "i-tofu",
    libraryTarget: "commonjs2"
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.OccurrenceOrderPlugin(true),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
    }),
    new ExtractTextPlugin({
      filename: utils.assetsPath('[name].css')
    }),
    new OptimizeCSSPlugin(),
   
    // new CopyWebpackPlugin([
    //   {
    //     from: path.resolve(__dirname, '../static'),
    //     to: config.build.assetsSubDirectory,
    //     ignore: ['.*']
    //   }
    // ])
  ]
})

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

打包后:

clipboard.png

example/main.js,引用

import Vue from 'vue';
import App from './App';
import router from './router';
// dev
// import 'ele/theme-chalk/src/index.scss';
// import Ipst from '@/index.js';

// dist
import '../dist/static/ipst.css';
import Ipst from '../dist/ipst.js';

Vue.config.productionTip = false;
Vue.use(Ipst);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
});
回答
編輯回答
孤巷
export NODE_ENV=development &&npm run dev

ipst是什么包,這個(gè)包有問(wèn)題吧,一個(gè)正常的包的啟動(dòng)不可能依賴完全環(huán)境變量的,像webpack本身就有默認(rèn)值。如果確定只有這個(gè)包有問(wèn)題建議去issue提一下,如果沒(méi)人維護(hù)就自己fork下來(lái)改。

2017年2月9日 03:51
編輯回答
孤巷

控制臺(tái)設(shè)置這個(gè)環(huán)境變量NODE_ENV='production'

2017年2月12日 04:04
編輯回答
影魅

需要使用 webpack defineplugin 這個(gè)插件

https://webpack.js.org/plugin...

https://segmentfault.com/l/15...

2018年7月7日 03:02